package com.kancy.stream.rabbit.message;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * ChannelMessage
 *
 * @author kancy
 * @date 2020/3/8 11:38
 */
public abstract class ChannelMessage<T> {

    public static final String HEADER_MESSAGE_TYPE = "message-type";
    public static final String HEADER_CHANNEL_KEY = "channel-key";
    public static final String HEADER_MESSAGE_KEY = "message-key";

    private String id = UUID.randomUUID().toString();

    public ChannelMessage() {
        setChannelKey(getChannelKey());
    }

    private Map<String, Object> headers = new HashMap();

    private T payload;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public T getPayload() {
        return payload;
    }

    public void setPayload(T payload) {
        this.payload = payload;
    }

    public Map<String, Object> getHeaders() {
        return headers;
    }

    public void setHeaders(Map<String, Object> headers) {
        this.headers = headers;
    }


    public void setHeader(String key, Object value){
        headers.put(key, value);
    }

    public Object getHeader(String key){
        return headers.get(key);
    }

    public void setMessageType(String messageType) {
        setHeader(HEADER_MESSAGE_TYPE,messageType);
    }

    public String getMessageType() {
        Object obj = headers.get(HEADER_MESSAGE_TYPE);
        if (Objects.nonNull(obj)){
            return String.valueOf(obj);
        }
        return null;
    }

    /**
     * 获取消息通道的key
     * @return
     */
    public abstract String getChannelKey();

    /**
     * 设置消息通道的key
     * @param channelKey
     */
    protected void setChannelKey(String channelKey){
        setHeader(HEADER_CHANNEL_KEY, channelKey);
    }

    @Override
    public String toString() {
        return "{" +
                "channelKey=" + getChannelKey() +
                ", payload=" + payload +
                ", headers=" + headers +
                '}';
    }
}
